﻿using DoNet.Common.Cache;
using DoNet.Token.Entitys;

namespace DoNet.Token
{
    /// <summary>
    /// 刷新令牌记录
    /// 可以改成数据库操作
    /// </summary>
    public class TokenLogService
    {
        /// <summary>
        /// 缓存Key
        /// </summary>
        private static string keyName = "TokenLogList";
        /// <summary>
        /// Token缓存列表
        /// </summary>
        private static ListCacheManager<string, SysAccessTokenLog> _cache = new ListCacheManager<string, SysAccessTokenLog>();

        /// <summary>
        /// 实现数据库存储逻辑
        /// </summary>
        /// <param name="oldAccessToken"></param>
        /// <param name="newAccessToken"></param>
        public static bool StoreTokenLog(string oldAccessToken, string newAccessToken)
        {
            try
            {
                long Id = 0;

                var list = _cache.GetListCopy(keyName);
                if (list.Count > 0)
                {
                    Id = list.Max(x => x.Id);
                }

                var model = new SysAccessTokenLog()
                {
                    Id = Id + 1,
                    OldAccessToken = oldAccessToken,
                    NewAccessToken = newAccessToken,
                    CreatedDate = DateTime.UtcNow
                };

                //实现数据库
                _cache.AppendToList(keyName, model);
                return true;
            }
            catch
            {

            }
            return false;
        }
    }
}
